<template>
  <div class="editor-selector">
    <!-- 编辑器类型选择 -->
    <div class="editor-type-selector" v-if="showTypeSelector">
      <el-radio-group v-model="currentEditorType" @change="handleEditorTypeChange" size="small">
        <el-radio-button label="rich">富文本编辑器</el-radio-button>
        <el-radio-button label="markdown">Markdown编辑器</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 编辑器容器 -->
    <div class="editor-container">
      <!-- 富文本编辑器 -->
      <SimpleRichTextEditor
        v-if="currentEditorType === 'rich'"
        ref="richEditorRef"
        v-model="content"
        :placeholder="placeholder"
        :readonly="readonly"
        :height="height"
        :show-word-count="showWordCount"
        :upload-url="uploadUrl"
        :upload-headers="uploadHeaders"
        :max-length="maxLength"
        @change="handleContentChange"
        @focus="handleFocus"
        @blur="handleBlur"
        @ready="handleReady"
      />

      <!-- Markdown编辑器 -->
      <MarkdownEditor
        v-else-if="currentEditorType === 'markdown'"
        ref="markdownEditorRef"
        v-model="content"
        :placeholder="placeholder"
        :readonly="readonly"
        :height="height"
        :show-status-bar="showStatusBar"
        :show-preview="showPreview"
        :sync-scroll="syncScroll"
        :theme="theme"
        :editor-mode="editorMode"
        :upload-url="uploadUrl"
        :upload-headers="uploadHeaders"
        :max-length="maxLength"
        :auto-save="autoSave"
        :auto-save-interval="autoSaveInterval"
        @change="handleContentChange"
        @save="handleSave"
        @focus="handleFocus"
        @blur="handleBlur"
        @ready="handleReady"
      />
    </div>

    <!-- 编辑器工具栏 -->
    <div class="editor-actions" v-if="showActions">
      <div class="actions-left">
        <el-button-group size="small">
          <el-button @click="handleSave" :loading="saving" type="primary">
            <el-icon><DocumentChecked /></el-icon>
            保存
          </el-button>
          <el-button @click="handlePreview" v-if="currentEditorType === 'rich'">
            <el-icon><View /></el-icon>
            预览
          </el-button>
          <el-button @click="handleFullscreen">
            <el-icon><FullScreen /></el-icon>
            全屏
          </el-button>
        </el-button-group>
      </div>

      <div class="actions-right">
        <el-button-group size="small">
          <el-button @click="handleUndo" :disabled="!canUndo">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button @click="handleRedo" :disabled="!canRedo">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>

        <el-dropdown @command="handleCommand" trigger="click">
          <el-button size="small">
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="clear">清空内容</el-dropdown-item>
              <el-dropdown-item command="word-count">字数统计</el-dropdown-item>
              <el-dropdown-item command="export-html" v-if="currentEditorType === 'markdown'">导出HTML</el-dropdown-item>
              <el-dropdown-item command="export-pdf" v-if="currentEditorType === 'markdown'">导出PDF</el-dropdown-item>
              <el-dropdown-item command="import-file" v-if="currentEditorType === 'markdown'">导入文件</el-dropdown-item>
              <el-dropdown-item command="settings">编辑器设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 编辑器设置对话框 -->
    <el-dialog v-model="settingsVisible" title="编辑器设置" width="500px">
      <el-form :model="settings" label-width="120px">
        <el-form-item label="默认编辑器">
          <el-select v-model="settings.defaultEditor" style="width: 100%">
            <el-option label="富文本编辑器" value="rich" />
            <el-option label="Markdown编辑器" value="markdown" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主题">
          <el-select v-model="settings.theme" style="width: 100%">
            <el-option label="自动" value="auto" />
            <el-option label="浅色" value="light" />
            <el-option label="深色" value="dark" />
          </el-select>
        </el-form-item>

        <el-form-item label="编辑器高度">
          <el-input-number v-model="settings.height" :min="300" :max="1000" :step="50" />
          <span style="margin-left: 8px; color: #909399;">px</span>
        </el-form-item>

        <el-form-item label="自动保存" v-if="currentEditorType === 'markdown'">
          <el-switch v-model="settings.autoSave" />
        </el-form-item>

        <el-form-item label="保存间隔" v-if="currentEditorType === 'markdown' && settings.autoSave">
          <el-input-number v-model="settings.autoSaveInterval" :min="10" :max="300" :step="10" />
          <span style="margin-left: 8px; color: #909399;">秒</span>
        </el-form-item>

        <el-form-item label="显示字数统计">
          <el-switch v-model="settings.showWordCount" />
        </el-form-item>

        <el-form-item label="显示状态栏" v-if="currentEditorType === 'markdown'">
          <el-switch v-model="settings.showStatusBar" />
        </el-form-item>

        <el-form-item label="同步滚动" v-if="currentEditorType === 'markdown'">
          <el-switch v-model="settings.syncScroll" />
        </el-form-item>

        <el-form-item label="编辑模式" v-if="currentEditorType === 'markdown'">
          <el-select v-model="settings.editorMode" style="width: 100%">
            <el-option label="普通模式" value="normal" />
            <el-option label="Vim模式" value="vim" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="settingsVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存设置</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="内容预览" width="80%" top="5vh">
      <div class="preview-content" v-html="previewContent"></div>
    </el-dialog>

    <!-- 字数统计对话框 -->
    <el-dialog v-model="wordCountVisible" title="字数统计" width="400px">
      <div class="word-count-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="字符数">{{ wordCount.characters }}</el-descriptions-item>
          <el-descriptions-item label="字符数(不含空格)">{{ wordCount.charactersNoSpaces }}</el-descriptions-item>
          <el-descriptions-item label="单词数">{{ wordCount.words }}</el-descriptions-item>
          <el-descriptions-item label="段落数">{{ wordCount.paragraphs }}</el-descriptions-item>
          <el-descriptions-item label="行数" v-if="currentEditorType === 'markdown'">{{ wordCount.lines }}</el-descriptions-item>
          <el-descriptions-item label="阅读时间">{{ readingTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="wordCountVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SimpleRichTextEditor from './SimpleRichTextEditor.vue'
import MarkdownEditor from './MarkdownEditor.vue'

// Props定义
interface Props {
  modelValue?: string
  editorType?: 'rich' | 'markdown'
  placeholder?: string
  readonly?: boolean
  height?: string | number
  showTypeSelector?: boolean
  showActions?: boolean
  showWordCount?: boolean
  showStatusBar?: boolean
  showPreview?: boolean
  syncScroll?: boolean
  theme?: 'light' | 'dark' | 'auto'
  editorMode?: 'normal' | 'vim'
  uploadUrl?: string
  uploadHeaders?: Record<string, string>
  maxLength?: number
  autoSave?: boolean
  autoSaveInterval?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  editorType: 'rich',
  placeholder: '请输入内容...',
  readonly: false,
  height: '500px',
  showTypeSelector: true,
  showActions: true,
  showWordCount: true,
  showStatusBar: true,
  showPreview: true,
  syncScroll: true,
  theme: 'auto',
  editorMode: 'normal',
  uploadUrl: '/api/upload/image',
  uploadHeaders: () => ({}),
  maxLength: 0,
  autoSave: false,
  autoSaveInterval: 30
})

// Emits定义
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'update:editorType', value: 'rich' | 'markdown'): void
  (e: 'change', value: string): void
  (e: 'save', value: string): void
  (e: 'focus'): void
  (e: 'blur'): void
  (e: 'ready'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const richEditorRef = ref()
const markdownEditorRef = ref()
const currentEditorType = ref(props.editorType)
const content = ref(props.modelValue)

// 状态
const saving = ref(false)
const canUndo = ref(false)
const canRedo = ref(false)

// 对话框状态
const settingsVisible = ref(false)
const previewVisible = ref(false)
const wordCountVisible = ref(false)

// 设置
const settings = reactive({
  defaultEditor: 'rich' as 'rich' | 'markdown',
  theme: 'auto' as 'light' | 'dark' | 'auto',
  height: 500,
  autoSave: false,
  autoSaveInterval: 30,
  showWordCount: true,
  showStatusBar: true,
  syncScroll: true,
  editorMode: 'normal' as 'normal' | 'vim'
})

// 计算属性
const currentEditor = computed(() => {
  return currentEditorType.value === 'rich' ? richEditorRef.value : markdownEditorRef.value
})

const previewContent = computed(() => {
  if (currentEditorType.value === 'rich') {
    return content.value
  } else {
    // Markdown预览需要渲染
    return markdownEditorRef.value?.renderedContent || content.value
  }
})

const wordCount = computed(() => {
  const text = content.value || ''
  const charactersNoSpaces = text.replace(/\s/g, '').length
  const lines = text.split('\n').length
  
  return {
    characters: text.length,
    charactersNoSpaces,
    words: text.trim() ? text.trim().split(/\s+/).length : 0,
    paragraphs: text.trim() ? text.split(/\n\s*\n/).length : 0,
    lines
  }
})

const readingTime = computed(() => {
  const wordsPerMinute = 200
  const minutes = Math.ceil(wordCount.value.words / wordsPerMinute)
  return `约 ${minutes} 分钟`
})

// 方法
const handleEditorTypeChange = (type: 'rich' | 'markdown') => {
  emit('update:editorType', type)
}

const handleContentChange = (value: string) => {
  content.value = value
  emit('update:modelValue', value)
  emit('change', value)
}

const handleSave = async () => {
  saving.value = true
  try {
    emit('save', content.value)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const handlePreview = () => {
  previewVisible.value = true
}

const handleFullscreen = () => {
  currentEditor.value?.toggleFullscreen?.()
}

const handleUndo = () => {
  currentEditor.value?.undo?.()
}

const handleRedo = () => {
  currentEditor.value?.redo?.()
}

const handleFocus = () => {
  emit('focus')
}

const handleBlur = () => {
  emit('blur')
}

const handleReady = () => {
  emit('ready')
}

const handleCommand = (command: string) => {
  switch (command) {
    case 'clear':
      handleClear()
      break
    case 'word-count':
      wordCountVisible.value = true
      break
    case 'export-html':
      currentEditor.value?.exportHTML?.()
      break
    case 'export-pdf':
      currentEditor.value?.exportPDF?.()
      break
    case 'import-file':
      currentEditor.value?.importFile?.()
      break
    case 'settings':
      settingsVisible.value = true
      break
  }
}

const handleClear = () => {
  ElMessageBox.confirm('确定要清空所有内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    content.value = ''
    emit('update:modelValue', '')
    emit('change', '')
    ElMessage.success('内容已清空')
  }).catch(() => {
    // 用户取消
  })
}

const saveSettings = () => {
  // 保存设置到localStorage
  localStorage.setItem('editor-settings', JSON.stringify(settings))
  settingsVisible.value = false
  ElMessage.success('设置已保存')
}

const loadSettings = () => {
  try {
    const saved = localStorage.getItem('editor-settings')
    if (saved) {
      Object.assign(settings, JSON.parse(saved))
    }
  } catch (error) {
    console.error('加载编辑器设置失败:', error)
  }
}

// 暴露方法给父组件
const getContent = () => {
  return currentEditor.value?.getContent?.() || content.value
}

const setContent = (value: string) => {
  content.value = value
  currentEditor.value?.setContent?.(value)
}

const focus = () => {
  currentEditor.value?.focus?.()
}

const blur = () => {
  currentEditor.value?.blur?.()
}

const clear = () => {
  handleClear()
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue
  }
})

watch(() => props.editorType, (newType) => {
  currentEditorType.value = newType
})

// 生命周期
onMounted(() => {
  loadSettings()
})

// 暴露方法给父组件
defineExpose({
  getContent,
  setContent,
  focus,
  blur,
  clear,
  save: handleSave,
  undo: handleUndo,
  redo: handleRedo,
  toggleFullscreen: handleFullscreen,
  showPreview: handlePreview,
  showWordCount: () => { wordCountVisible.value = true },
  showSettings: () => { settingsVisible.value = true }
})
</script>

<style lang="scss" scoped>
.editor-selector {
  .editor-type-selector {
    margin-bottom: 12px;
    padding: 12px;
    background: #f8f9fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px 4px 0 0;
  }

  .editor-container {
    border-radius: 0 0 4px 4px;
  }

  .editor-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f8f9fa;
    border: 1px solid #e4e7ed;
    border-top: none;
    border-radius: 0 0 4px 4px;

    .actions-left, .actions-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .preview-content {
    max-height: 70vh;
    overflow-y: auto;
    padding: 20px;
    font-size: 14px;
    line-height: 1.6;
  }

  .word-count-detail {
    .el-descriptions {
      margin: 16px 0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .editor-selector {
    .editor-actions {
      flex-direction: column;
      gap: 8px;
      align-items: stretch;

      .actions-left, .actions-right {
        justify-content: center;
      }
    }
  }
}
</style>
